import router from "@/router";
import store from "@/store";
import { getRequest } from "./api";

// 初始化菜单
export const initMenu = (router, store) => {
    //如果菜单有数据就不初始化
    if (store.state.routes.length > 0) {
        return;
    }
    // 去发送请求去后台加载
    getRequest("/system/cfg/menu").then(data => {
        if (data) {
            // 格式化Router
            let fmtRoutes = formatRoutes(data);
            // 添加到路由
            router.addRoutes(fmtRoutes);
            // 将数据存入vuex
            store.commit('initRoutes',fmtRoutes)
        }
    })
}
// 格式化后端数据
export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            iconCls,
            children
        } = router;
        if (children && children instanceof Array) {
            // 递归
            children = formatRoutes(children)
        }
        // 格式化数据
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            component(resolve) {

                if (component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'], resolve);
                }else if (component.startsWith('Emp')) {
                    require(['../views/emp/' + component + '.vue'], resolve);
                } else if (component.startsWith('Per')) {
                    require(['../views/per/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sal')) {
                    require(['../views/sal/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sta')) {
                    require(['../views/sta/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sys')) {
                    require(['../views/sys/' + component + '.vue'], resolve);
                }
            }
        }
        // 把格式化好的fmRouter放到数组中
        fmtRoutes.push(fmRouter)
    });
    return fmtRoutes;
}
